#!/bin/bash
# 20220715


# 打包 rpm 需要修改的参数
serverName=web01
serverVersion=1.0.0
installPath="/usr/local"

# 获取当前绝对路径
workdir=`cd $(dirname $0); pwd`

# 检查是否安装了 rpmbuild 工具，没有需要手动安装
checkRpmbuild() {
    if ! type rpmbuild > /dev/null 2>&1
    then
        echo rpmbuild is required. Run "yum install rpm-build" to install rpmbuild. Aborting...
        exit 1
    fi
}

# 通过参数修改打包 rpm 需要修改的参数
setConfig() {
    while getopts ":n:v:p:" opt; do
        case $opt in
            n)
                serverName=$OPTARG
                ;;
            v)
                serverVersion=$OPTARG
                ;;
            p)
                installPath=$OPTARG
                ;;
            ?)
                echo "帮助信息:"
                echo "  -n 服务名称 (当前: $serverName)"
                echo "  -v 服务版本 (当前: $serverVersion)"
                echo "  -p 安装路径 (当前: $installPath)"
                echo "  例: ./rpmbuild.sh -n web01 -v 1.0.0 -p /usr/local"
                exit 1
                ;;
        esac
    done
}

# 通过模板生成服务启动需要的 service 配置文件
makeServiceConf() {
    cp -f web01.service.template ${serverName}.service
    sed -i "s#{{ serverName }}#${serverName}#g" ${serverName}.service
    sed -i "s#{{ installPath }}#${installPath}#" ${serverName}.service
}

# 通过模板生成 rpmbuild 需要的 spec 配置文件
makeSpecConf() {
    cp -f web01.spec.template ${serverName}.spec
    sed -i "s#{{ serverName }}#${serverName}#g" ${serverName}.spec
    sed -i "s#{{ serverVersion }}#${serverVersion}#" ${serverName}.spec
    sed -i "s#{{ installPath }}#${installPath}#" ${serverName}.spec
}

# 生成 rpmbuild 需要的源码包
makeSource0() {
    cd ${workdir}/..
    # 编译
    sed -i "s/^BINARY=\".*\"/BINARY=\"${serverName}\"/" Makefile
    make
    # 打包
    mv ${serverName} ${workdir}
    cp web01.yaml ${workdir}/${serverName}.yaml
    cd ${workdir}
    rm -f rpmbuild/BUILD/*
    tar zcvf rpmbuild/BUILD/source.tar.gz ${serverName} ${serverName}.service ${serverName}.yaml
    chmod 755 rpmbuild/BUILD/source.tar.gz
}

# 生成 rpm 包
makeRpmPackage() {
    cd ${workdir}/rpmbuild
    rpmbuild --define "_topdir ${workdir}/rpmbuild" -bb --rmsource ../${serverName}.spec

    mv RPMS/x86_64/${serverName}-*.rpm ..
}

# 简单清理一下过程文件
clearTmpFile() {
    cd ${workdir}
    rm -f ${serverName}.spec ${serverName}.service ${serverName}.yaml ${serverName}
}

main() {
    checkRpmbuild
    setConfig $@
    makeServiceConf
    makeSource0
    makeSpecConf
    makeRpmPackage
    clearTmpFile
}

main $@